package com.googlecode.connectlet.crypto;

import java.io.IOException;
import java.io.PrintStream;
import java.security.AlgorithmParametersSpi;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.InvalidParameterSpecException;

import javax.crypto.spec.IvParameterSpec;

import com.googlecode.connectlet.util.Bytes;
import com.googlecode.connectlet.util.ByteArrayQueue;

public final class IvParameters extends AlgorithmParametersSpi {
	private byte[] iv;

	@Override
	protected byte[] engineGetEncoded() throws IOException {
		return iv;
	}

	@Override
	protected byte[] engineGetEncoded(String format) throws IOException {
		return iv;
	}

	@Override
	protected <T extends AlgorithmParameterSpec> T engineGetParameterSpec(
			Class<T> paramSpec) throws InvalidParameterSpecException {
		if (paramSpec.isAssignableFrom(IvParameterSpec.class)) {
			return paramSpec.cast(new IvParameterSpec(iv));
		}
		throw new InvalidParameterSpecException("paramSpec must be IvParameterSpec");
	}

	@Override
	protected void engineInit(AlgorithmParameterSpec paramSpec)
			throws InvalidParameterSpecException {
		if (paramSpec instanceof IvParameterSpec) {
			iv = ((IvParameterSpec) paramSpec).getIV();
		} else {
			throw new InvalidParameterSpecException("IvParameterSpec required");
		}
	}

	@Override
	protected void engineInit(byte[] params) throws IOException {
		iv = params;
	}

	@Override
	protected void engineInit(byte[] params, String format) throws IOException {
		iv = params;
	}

	@Override
	protected String engineToString() {
		ByteArrayQueue baq = new ByteArrayQueue();
		PrintStream out = new PrintStream(baq.getOutputStream());
		out.println("Initialization Vector:");
		Bytes.dump(out, iv);
		return baq.toString();
	}
}